from __future__ import absolute_import
import logging
import fnmatch
import os
from os.path import dirname, exists
from forest.api import Command, get_tool
#from forest.commands.live.buildliveimage import BuildLiveImage

logger = logging.getLogger('forest.commands.forest.CreateInitrd')

move = get_tool('system.move')
copy = get_tool('system.copy')

class CreateInitrd(Command):
    ''' Builds a live installer image as per forest.image.

    '''
    __register__ = 'commands.forest.CreateInitrd'

    # TODO: refactor into
    def get_iso_root(self):
        return os.path.join(self._config.get_build_root(), 'isoroot')

    def join_iso_root(self, *args):
        return os.path.join(self._config.get_build_root(), 'isoroot', *args)

    def run(self, config):
        # create a directory for the iso
        self.args = config.get('forest.image', False)
        self._config = config

        if not self.args:
            return

        self.exclusions = self.args.get('exclude', [])

        if self.args.get('type') == 'initrd':
            kerneldest, initdest = self.args.get('destination').split(' ')
            self.buildinitrdimage(config, initdest)

        elif self.args.get('type') == 'iso':
            self.buildinitrdimage(config, self.join_iso_root('isolinux', 'initrd.img'))

    def buildinitrdimage(self, config, dest):
        install_root = config.get_install_root()
        logging.info('Building initrd installer image...')

        if not exists(dirname(dest)) and dirname(dest) != '':
            print dest
            get_tool('system.mkdir')(dirname(dest))

        get_tool('image.mkcpio')(install_root, dest, compression="gzip", compressargs=["-9"], exclude=self.exclude)
        # old dracut code for live images
        #if not exists('isoroot/isolinux/initrd.img'):
        #    # build a dest system compatable initrd
        #    initrdtmp = '/tmp/initrd.img'
        #    kernel = self.generate_dracut_initrd(config, initrdtmp)

        #    logger.debug('Moving image from %s %s', install_root, install_root+initrdtmp)
        #    move(install_root+initrdtmp, 'isoroot/isolinux/initrd.img')
        #self.buildliveimage(config, destination='isoroot/isolinux/initrd.img')

    def exclude(self, item):
        include = True

        for pattern in self.exclusions:
            mat = fnmatch.fnmatch(item, pattern)
            if mat:
                include = False

        if include is False:
            logger.log(5, 'Excluding %s', item)
            pass
        return include
